package cn.harmonyoslearn.navrouter.utils;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;

public class CmdUtil {
    public static void run(String command, @NotNull AnActionEvent e) {
        LogUtil.i("CmdUtil.run", "执行命令：" + command);
        // 获取当前操作系统的类型
        String projectRootPath = Objects.requireNonNull(e.getProject()).getBasePath();

        // 根据操作系统选择合适的命令执行器
        boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
        String[] cmd = isWindows ? new String[]{"cmd", "/c", command} : new String[]{"sh", "-c", command};

        try {
            // 创建ProcessBuilder实例
            ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            // 设置工作目录为项目的根目录
            if (projectRootPath != null) {
                processBuilder.directory(new java.io.File(projectRootPath));
            }
            // 将错误流重定向到标准输出流
            processBuilder.redirectErrorStream(true);

            // 启动进程
            Process process = processBuilder.start();

            // 读取进程的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            LogUtil.i("CmdUtil.run", output.toString());

            // 等待进程结束
            int exitCode = process.waitFor();

            // 根据退出代码判断命令是否执行成功
            if (exitCode == 0) {
                LogUtil.i("CmdUtil.run", command + "执行成功，" + "初始化成功");
                Messages.showInfoMessage(command + "执行成功" + ", 初始化成功", "成功");
            } else {
                LogUtil.e("CmdUtil.run", command + "执行失败，请手动执行ohpm install，" + "或者手动同步一下项目便可。");
                Messages.showErrorDialog(command + "执行失败，请手动执行ohpm install，" + "或者手动同步一下项目便可。", "错误提示");
            }
        } catch (IOException | InterruptedException ex) {
            // 处理异常情况
            Messages.showErrorDialog(command + "执行失败，An error occurred: " + ex.getMessage(), "Error");
            LogUtil.e("CmdUtil.run", command + "执行失败：An error occurred: " + ex.getMessage());
        }
    }
}
